<template>
  <div>
    <router-view>
      <div class="box">
        <!-- <div></div> -->
        <el-card class="box-card">
          <template #header>
            <div style="font-size: 20px; font-weight: 600">
              <span>科室管理</span>
            </div>
            <div style="height: 2vh"></div>
            <div class="header">
              <div class="left">
                <el-input
                  style="width: 150px"
                  v-model="departvalue"
                  @input="searchDepart"
                  placeholder="输入一级科室名称"
                />
              </div>
              <div class="right">
                <!-- <el-button type="danger" @click="deleteBatches">批量删除</el-button> -->
                <el-button type="primary" @click="addOffice">新增科室</el-button>
              </div>
            </div>
          </template>

          <div style="margin-bottom: 2vh"></div>
          <el-table
            v-loading="loading"
            ref="treeTable"
            :data="pageDatas"
            style="width: 100%; margin-bottom: 20px"
            row-key="id"
            stripe="true"
            @select-all="clickSelectAll"
            @select="rowSelect"
          >
            <el-table-column align="center" type="selection" width="200" fixed="left" />
            <el-table-column align="left" prop="name" label="科室名称" width="200" fixed="left" />
            <el-table-column align="center" prop="heat" label="热度" width="240" />
            <el-table-column align="center" prop="local" label="地点" />
            <el-table-column align="center" prop="num" label="医生数量" width="200" />
            <el-table-column align="center" prop="create_time" label="创建时间" width="250" />
            <el-table-column align="center" label="操作" width="150" fixed="right">
              <!-- <template #default="scope">
              <img
                style="width: 20px; height: 20px; margin-right: 10px"
                src="../../assets/编辑.png"
                alt=""
                @click="handleEdit(scope.$index, scope.row)"
              />
              <img
                style="width: 20px; height: 20px"
                src="../../assets/删除-01.png"
                alt=""
                @click="handleDelete(scope.$index, scope.row)"
              />
            </template> -->
              <template #default="scope">
                <div style="display: flex; align-items: center; justify-content: center">
                  <el-button
                    type="primary"
                    plain
                    size="small"
                    @click="handleEdit(scope.$index, scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    plain
                    size="small"
                    @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div style="display: flex; justify-content: center">
            <el-pagination
              style="padding: 10px"
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 30]"
              layout="total, sizes,->, prev, pager, next, jumper"
              :total="listNum"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
      <!-- 新增/编辑页面 -->
      <el-dialog
        v-model="dialogFormVisible"
        @close="cancel()"
        width="50%"
        :title="form.id <= 0 ? '新增科室信息' : '编辑科室信息'"
      >
        <div class="window">
          <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="科室名称" prop="name">
              <el-input style="width: 300px" v-model="form.name" placeholder="输入科室名称" />
            </el-form-item>
            <el-form-item label="上级科室" prop="pid">
              <el-select v-model="form.pid" clearable placeholder="无">
                <el-option
                  v-for="item in departList"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                />
              </el-select>
              <span class="hint">注：一级科室无需选择，可清除选择</span>
            </el-form-item>
            <el-form-item label="科室位置" prop="local">
              <el-input style="width: 300px" v-model="form.local" placeholder="输入科室位置" />
            </el-form-item>
            <el-form-item label="科室详情" prop="details">
              <vue-ueditor-wrap
                v-model="form.details"
                :config="editorConfig"
                style="width: 680px; z-index: 1"
              ></vue-ueditor-wrap>
            </el-form-item>
            <div style="direction: rtl">
              <el-form-item>
                <el-button type="primary" @click="affirm(ruleFormRef)" v-if="form.id <= 0"
                  >新增</el-button
                >
                <el-button type="primary" @click="affirm(ruleFormRef)" v-else>保存</el-button>
                <div style="width: 10px"></div>
                <el-button @click="cancel(ruleFormRef)">取消</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </el-dialog>
    </router-view>
  </div>
</template>

<script setup>
  import { ref, reactive, computed } from 'vue';
  import { depart, addDepart, doctor, deleteDepart } from '../../api/departMents';
  import { Loading } from '@element-plus/icons-vue';
  const form = reactive({
    name: '',
    local: '',
    pid: '',
    details: '',
    id: '',
  });
  // UEditor配置
  const editorConfig = reactive({
    autoHeightEnabled: false,
    initialFrameHeight: 200,
    initialFrameWidth: '100%',
    UEDITOR_HOME_URL: '/ueditor/', // 访问 UEditor 静态资源的根路径publc里面的名称
    serverUrl: '/pc/pc/Fileimg/uderto', // 服务端接⼝
    uploadUrl: '/pc/pc/Fileimg/uderto' + '/kjyl-server-doctor/doctor/file/uploadFile',
    // enableAutoSave: true, // 开启从草稿箱恢复功能需要⼿动设置固定的 editorId，否则组件会默认随机⼀个，如果页⾯刷新，下次渲染的时候 editorId 会重新随机，
  });
  const dialogFormVisible = ref(false); //弹窗状态

  const listNum = ref(0);
  const currentPage = ref(1);
  const pageSize = ref(10);
  const loading = ref(true);
  const ruleFormRef = ref(); //页面表单实例
  const treeTable = ref(null);
  const departList = ref([]);
  const departvalue = ref('');
  const searchData = ref([]);
  const rules = reactive({
    name: [
      {
        required: true,
        message: '请输入科室名称',
        trigger: 'change',
      },
    ],
    pid: [
      {
        required: false,
        message: '请选择上级科室',
        trigger: 'change',
      },
    ],
    local: [
      {
        required: true,
        message: '请输入科室位置',
        trigger: 'change',
      },
    ],
    details: [
      {
        required: true,
        message: '请输入科室详情',
        trigger: 'change',
      },
    ],
  });
  //分页数据显示
  const pageDatas = computed(() => {
    let a = [];
    for (
      let i = (currentPage.value - 1) * pageSize.value;
      i < currentPage.value * pageSize.value;
      i++
    ) {
      if (searchData.value[i]) {
        a.push(searchData.value[i]);
      }
    }
    console.log('123', a);
    return a;
  });
  // 搜索
  const searchDepart = () => {
    console.log(departvalue.value);
    searchData.value = departList.value.filter(function (item) {
      if (item.name.indexOf(departvalue.value) > -1) {
        return item;
      }
    });
    listNum.value = searchData.value.length;
  };
  // 请求列表
  const requestList = () => {
    doctor().then((res) => {
      console.log('医生列表', res);
      depart().then((ress) => {
        console.log('科室列表', ress);
        let treeid = 0; //初始为一级列表，默认id为0
        departList.value = [];
        changeTree(ress.data, treeid, departList.value, res.data);
        for (let i = 0; i < departList.value.length; i++) {
          for (let j = 0; j < departList.value[i].children.length; j++) {
            departList.value[i].num += departList.value[i].children[j].num;
          }
        }
        searchDepart();
        loading.value = false;
        console.log(searchData.value);
      });
    });
  };
  requestList();
  // 每页显示数量改变
  const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1;
    console.log(`${val} items per page`);
  };
  // 页码数改变
  const handleCurrentChange = (val) => {
    currentPage.value = val;
    console.log(`current page: ${val}`);
  };
  // 编辑
  const handleEdit = (index, row) => {
    dialogFormVisible.value = true;
    form.id = row.id;
    form.name = row.name;
    form.local = row.local;
    form.pid = row.pid == 0 ? '' : row.pid;
    form.details = row.details;
    form.id = row.id;
    console.log(index, row);
  };
  // 删除
  const handleDelete = (index, row) => {
    console.log(index, row);
    ElMessageBox.confirm('是否确认删除?', '删除科室', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        let arr = [];
        arr.push(row.id);
        if (row.children) {
          for (let i = 0; i < row.children.length; i++) {
            arr.push(row.children[i].id);
          }
        }
        for (let i = 0; i < arr.length; i++) {
          deleteDepart({
            id: arr[i],
          });
        }
        ElMessage({
          type: 'success',
          message: '删除成功',
        });
        requestList();
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        });
      });
  };
  // 批量删除
  const deleteBatches = () => {};
  // 新增科室
  const addOffice = () => {
    form.id = '';
    // clearForm();
    dialogFormVisible.value = true;
    ruleFormRef.value.clearValidate();
  };
  // 清空表单
  const clearForm = () => {
    form.name = '';
    form.local = '';
    form.pid = '';
    form.details = '';
    form.id = '';
  };
  // 取消
  const cancel = (formEl) => {
    clearForm();
    formEl.resetFields();
    dialogFormVisible.value = false;
  };
  // 确认新增/编辑科室
  const affirm = async (formEl) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        addDepart(form).then((res) => {
          console.log(res);
          formEl.resetFields();
          if (res.code == 1) {
            ElMessage({
              type: 'success',
              message: `${res.msg}`,
            });
            dialogFormVisible.value = false;
          } else {
            ElMessage({
              type: 'error',
              message: '操作失败',
            });
          }
          requestList();
        });
        console.log('submit!');
      } else {
        console.log('error submit!', fields);
      }
    });
  };
  // 多选
  const eachList = (list, status) => {
    for (let i = 0; i < list.length; i++) {
      if (list[i].children) {
        for (let k = 0; k < list[i].children.length; k++) {
          treeTable.value.toggleRowSelection(list[i].children[k], status);
        }
      }
    }
  };
  const clickSelectAll = (selection) => {
    let selectStatus = treeTable.value.store.states.isAllSelected._value;
    console.log(selectStatus);
    console.log(selection);
    eachList(departList.value, selectStatus);
  };
  const rowSelect = (selection, row) => {
    console.log(selection);
    console.log(row);
    if (row.children) {
      for (let i = 0; i < row.children.length; i++) {
        console.log(row.children[i]);
        treeTable.value.toggleRowSelection(row.children[i]);
      }
    }
  };
  // 修改数据为树形数据
  const changeTree = (datalist, id, newArr, doctor) => {
    for (let i = 0; i < datalist.length; i++) {
      if (datalist[i].pid == id) {
        datalist[i].num = 0;
        for (let j = 0; j < doctor.length; j++) {
          if (datalist[i].id == doctor[j].depart_id) {
            datalist[i].num++;
          }
        }
        newArr.push(datalist[i]);
      }
    }
    for (let i = 0; i < newArr.length; i++) {
      newArr[i].children = [];
      changeTree(datalist, newArr[i].id, newArr[i].children, doctor);
      if (newArr[i].children.length == 0) {
        delete newArr.children;
      }
    }
  };
</script>

<style lang="scss" scoped>
  .box {
    width: 100%;
    background-color: rgb(255, 255, 255);
    overflow-y: scroll;
  }
  .header {
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding: 10px 20px;
  }
  .head_word {
    width: 100%;
    padding: 10px 20px;
    border-bottom: 1px solid #e5e5e5;
    margin-bottom: 20px;
    color: #427eff;
  }

  .window {
    width: 100%;
    // overflow-x: scroll;
    padding: 10px;
    background-color: white;
  }
  .hint {
    margin-left: 10px;
    color: #a6a6a6;
    font-size: 14px;
  }
  .tableHeader {
    color: white;
  }
</style>
